import React from 'react';
import { Grade, getScoreLevelText, subjectOptions } from '../types';

interface GradeDetailModalProps {
  isOpen: boolean;
  grade: Grade | null;
  onClose: () => void;
}

const GradeDetailModal: React.FC<GradeDetailModalProps> = ({
  isOpen,
  grade,
  onClose,
}) => {
  // 如果模态框未打开或没有成绩数据，则不渲染
  if (!isOpen || !grade) return null;

  // 处理ESC键关闭模态框
  const handleKeyDown = (e: KeyboardEvent) => {
    if (e.key === 'Escape') {
      onClose();
    }
  };

  // 点击模态框外部关闭模态框
  const handleOverlayClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  // 在组件挂载时添加键盘事件监听
  React.useEffect(() => {
    if (isOpen) {
      document.addEventListener('keydown', handleKeyDown);
    }
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [isOpen, onClose]);

  // 获取科目的满分
  const getMaxScoreForSubject = (subject: string): number => {
    const foundSubject = subjectOptions.find(s => s.value === subject);
    return foundSubject ? foundSubject.maxScore : 100;
  };

  // 计算分数百分比
  const calculatePercentage = (score: number, maxScore: number): number => {
    return Math.round((score / maxScore) * 100);
  };

  // 获取分数等级的样式类
  const getScoreLevelClass = (score: number, subject: string): string => {
    const level = getScoreLevelText(score, subject);
    if (level.includes('优秀')) return 'score-level-excellent';
    if (level.includes('良好')) return 'score-level-good';
    if (level.includes('及格')) return 'score-level-pass';
    if (level.includes('不及格')) return 'score-level-fail';
    return '';
  };

  const maxScore = getMaxScoreForSubject(grade.subject);
  const percentage = calculatePercentage(grade.score, maxScore);

  return (
    <div className="modal-overlay" onClick={handleOverlayClick}>
      <div className="modal-content">
        <div className="modal-header">
          <h2 className="modal-title">成绩详情</h2>
          <button className="modal-close" onClick={onClose}>&times;</button>
        </div>
        <div className="modal-body">
          {grade && (
            <div className="grade-detail-container">
              <div className="grade-detail-header">
                <div className="student-info">
                  <h3>{grade.studentName}</h3>
                  <p className="student-id">学号: {grade.studentId}</p>
                </div>
                <div className="score-overview">
                  <span className={`score-value ${getScoreLevelClass(grade.score, grade.subject)}`}>
                    {grade.score}
                  </span>
                  <span className="max-score">/{maxScore}</span>
                </div>
              </div>
              
              <div className="grade-detail-content">
                <div className="detail-row">
                  <div className="detail-label">学期</div>
                  <div className="detail-value">{grade.term}</div>
                </div>
                <div className="detail-row">
                  <div className="detail-label">考试类型</div>
                  <div className="detail-value">{grade.examType}</div>
                </div>
                <div className="detail-row">
                  <div className="detail-label">科目</div>
                  <div className="detail-value">
                    {subjectOptions.find(s => s.value === grade.subject)?.label || grade.subject}
                  </div>
                </div>
                <div className="detail-row">
                  <div className="detail-label">分数等级</div>
                  <div className={`detail-value score-level-tag ${getScoreLevelClass(grade.score, grade.subject)}`}>
                    {getScoreLevelText(grade.score, grade.subject)}
                  </div>
                </div>
                <div className="detail-row">
                  <div className="detail-label">百分比</div>
                  <div className="detail-value">
                    <div className="percentage-bar">
                      <div 
                        className={`percentage-fill ${getScoreLevelClass(grade.score, grade.subject)}`}
                        style={{ width: `${percentage}%` }}
                      ></div>
                    </div>
                    <span className="percentage-text">{percentage}%</span>
                  </div>
                </div>
                {grade.remark && (
                  <div className="detail-row">
                    <div className="detail-label">备注</div>
                    <div className="detail-value">{grade.remark}</div>
                  </div>
                )}
                <div className="detail-row">
                  <div className="detail-label">创建时间</div>
                  <div className="detail-value">
                    {new Date(grade.createdAt).toLocaleString()}
                  </div>
                </div>
                <div className="detail-row">
                  <div className="detail-label">创建者</div>
                  <div className="detail-value">{grade.createdBy}</div>
                </div>
                {grade.updatedAt !== grade.createdAt && (
                  <>
                    <div className="detail-row">
                      <div className="detail-label">更新时间</div>
                      <div className="detail-value">
                        {new Date(grade.updatedAt).toLocaleString()}
                      </div>
                    </div>
                    <div className="detail-row">
                      <div className="detail-label">更新者</div>
                      <div className="detail-value">{grade.updatedBy}</div>
                    </div>
                  </>
                )}
              </div>
            </div>
          )}
        </div>
        <div className="modal-footer">
          <button className="btn-primary" onClick={onClose}>关闭</button>
        </div>
      </div>
    </div>
  );
};

export default GradeDetailModal;